<template>
  <div class="arpe-container">
    <!-- Header -->
    <div class="arpe-header">
      <div class="arpe-title">轧制参数仿真模型</div>
    </div>
    <div class="arpe-content-layout">
      <!-- 上区域 -->
      <div class="arpe-section top-section">
        <div class="top-flex">
          <!-- 新增：出口厚度实际值小卡片 S1~S5 及机架前 -->
          <div class="thickness-card thickness-card-before semitransp_box">
            <p>机架前入口厚度</p>
            <p>{{ thicknessValues.BEFORE }}mm</p>
          </div>
          <div class="thickness-card thickness-card-s1 semitransp_box">
            <p>S1出口厚度</p>
            <p>{{ thicknessValues.STD1A }}mm</p>
          </div>
          <div class="thickness-card thickness-card-s4 semitransp_box">
            <p>S4出口厚度</p>
            <p>{{ thicknessValues.STD4A }}mm</p>
          </div>
          <div class="thickness-card thickness-card-s5 semitransp_box">
            <p>S5出口厚度</p>
            <p>{{ thicknessValues.STD5A }}mm</p>
          </div>
          <div class="top-svg">
            <img src="../../assets/svgs/TCM2280S.svg" alt="轧机SVG" />
          </div>
          <div class="top-table">
            <div class="table-title">当前卷和下一卷信息</div>
            <el-table :data="tableData" style="width: 100%;" border size="small">
              <el-table-column prop="ITEM" label="" width="60" />
              <el-table-column prop="COIL_ID" label="卷号" width="100" />
              <el-table-column prop="STEEL_GRADE" label="钢种" />
              <el-table-column prop="EN_WIDTH" label="宽度[mm]" />
              <el-table-column prop="EN_THICK" label="入口厚度[mm]" />
              <el-table-column prop="EX_THICK" label="出口厚度[mm]" />
              <el-table-column prop="YP" label="屈服强度" />
              <el-table-column prop="YPINDEX" label="屈服分档" />
              <el-table-column prop="WIDINDEX" label="宽度分档" />
              <el-table-column prop="THKINDEX" label="厚度分档" />
            </el-table>
          </div>
        </div>
      </div>
      <!-- 中间区域 -->
      <div class="arpe-section middle-section">
        <el-table :data="middleTableDataall" style="width: 100%; margin-top: 10px;" border size="small">
          <el-table-column prop="ITEM" label="参数" />
          <el-table-column prop="UNIT" label="计量单位" />
          <el-table-column label="S5机架" header-align="center">
            <el-table-column prop="STD5B" label="计算值" />
            <el-table-column prop="STD5" label="设定值" />
            <el-table-column prop="STD5A" label="实际值">
              <template #default="{ row }">
                <span style="color:#00ff9d; font-weight:bold;">{{ row.STD5A }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="S4机架" header-align="center">
            <el-table-column prop="STD4B" label="计算值" />
            <el-table-column prop="STD4" label="设定值" />
            <el-table-column prop="STD4A" label="实际值">
              <template #default="{ row }">
                <span style="color:#00ff9d; font-weight:bold;">{{ row.STD4A }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="S3机架" header-align="center">
            <el-table-column prop="STD3B" label="计算值" />
            <el-table-column prop="STD3" label="设定值" />
            <el-table-column prop="STD3A" label="实际值">
              <template #default="{ row }">
                <span style="color:#00ff9d; font-weight:bold;">{{ row.STD3A }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="S2机架" header-align="center">
            <el-table-column prop="STD2B" label="计算值" />
            <el-table-column prop="STD2" label="设定值" />
            <el-table-column prop="STD2A" label="实际值">
              <template #default="{ row }">
                <span style="color:#00ff9d; font-weight:bold;">{{ row.STD2A }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="S1机架" header-align="center">
            <el-table-column prop="STD1B" label="计算值" />
            <el-table-column prop="STD1" label="设定值" />
            <el-table-column prop="STD1A" label="实际值">
              <template #default="{ row }">
                <span style="color:#00ff9d; font-weight:bold;">{{ row.STD1A }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="BEFORE" label="机架前" />
        </el-table>
      </div>
      <!-- 下区域 -->
      <div class="arpe-section bottom-section">
        <div class="bottom-charts">
          <div class="chart-card" v-for="(item, idx) in chartList" :key="item.title">
            <div class="chart-title">{{ item.title }}</div>
            <div :ref="el => chartRefs[idx] = el" class="echart-box"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue';
import * as echarts from 'echarts';
import { rollingSimulationApi } from '/@/api/RollingSimulation/index';
import { useUserStore } from '/@/store/modules/system/user';

const tableData = ref<any[]>([]);
const middleTableData = ref<any[]>([]);
const middleTableDataall = ref<any[]>([]);
const chartList = ref<any[]>([]);
const chartRefs = Array(5).fill(null);
let chartInstances: echarts.ECharts[] = [];
let timer: any = null;
const data = ref([
  {menuName: "rollingsimulations",menuTitle: '轧制仿真主页',menuId:'1'},{menuName: "acidrollingplan",menuTitle: '酸轧计划仿真'},{menuName: "acidrollingproduct",menuTitle: '酸轧生产实绩'},{menuName: "rollingsimulationl",menuTitle: '轧制仿真计算'},{menuName: "rollingAccuracy",menuTitle: '轧制仿真模型精度'},{menuName: "case",menuTitle: '仿真案例管理'},{menuName: "loadDistribution",menuTitle: '负荷分配优化'},{menuName: "historyOptimizationRecord",menuTitle: '历史推优记录'},{menuName: "steeloptimization",menuTitle: '高强钢张力优化'},{menuName: "processoptimization",menuTitle: '工艺参数推优'}
]);

const arr = [
  // 出口厚度
  ["M_400_207NI", "M_400_212NI", "", "", "M_400_205NI", "", "", "", "", "", ""],
  // 速度
  ["M_400_262NI", "M_403_123NI", "M_506_123NI", "M_506_113NI", "M_403_113NI", "", "M_506_142NI", "M_506_132NI", "M_506_122NI", "M_506_112NI", "M_506_102NI"],
  // 前滑
  ["M_400_40BR", "M_400_38BR", "", "", "M_400_32BR", "", "M_400_39BR", "M_400_37BR", "", "", "M_400_34BR"],
  // 轧制力
  ["M_505_152NI", "M_505_151NI", "M_505_150NI", "M_505_149NI", "M_505_148NI", "", "M_505_136NI", "M_505_135NI", "M_505_134NI", "M_505_133NI", "M_505_132NI"],
  // 下一卷轧制力
  ["M_406_422NI", "M_406_392NI", "M_406_362NI", "M_406_332NI", "M_406_302NI", "", "", "", "", "", ""],
  // 转矩
  ["M_506_144NI", "M_506_134NI", "M_506_124NI", "M_506_114NI", "M_506_104NI", "", "", "", "", "", ""],
  // 电机功率
  ["M_505_248NI", "M_505_247NI", "M_505_246NI", "M_505_245NI", "M_505_244NI", "", "", "", "", "", ""],
  // 辊缝
  ["L_RT_GAGREF_5", "L_RT_GAGREF_4", "L_RT_GAGREF_3", "L_RT_GAGREF_2", "L_RT_GAGREF_1", "", "L_RT_GAGREF_5", "L_RT_GAGREF_4", "L_RT_GAGREF_3", "L_RT_GAGREF_2", "L_RT_GAGREF_1"],
  // 工作辊弯辊力
  ["M_505_163NI", "M_505_162NI", "M_505_161NI", "M_505_160NI", "M_505_159NI", "", "M_505_147NI", "M_505_146NI", "M_505_145NI", "M_505_144NI", "M_505_143NI"],
  // 中间辊弯辊力
  ["M_505_225NI", "M_505_224NI", "M_505_223NI", "M_505_222NI", "M_505_221NI", "", "M_505_215NI", "M_505_214NI", "M_505_213NI", "M_505_212NI", "M_505_211NI"],
  // 辊径
  ["M_535_115NI", "M_534_115NI", "M_533_115NI", "M_532_115NI", "M_531_115NI", "", "", "", "", "", ""],
  // 张力
  ["M_400_352NI", "M_400_350NI", "M_400_348NI", "M_400_346NI", "M_400_344NI", "M_400_342NI", "M_400_349NI", "M_400_347NI", "M_400_345NI", "M_400_343NI", "M_400_341NI"],
  // 工作辊辊径
  ["L_TCM_S5BWRD", "L_TCM_S4BWRD", "L_TCM_S3BWRD", "L_TCM_S2BWRD", "L_TCM_S1BWRD", "", "", "", "", "", ""],
  // 压下率
  ["", "", "", "", "", "", "", "", "", "", ""],
  // 压下量
  ["", "", "", "", "", "", "", "", "", "", ""],
];

function formatNumber(val: any, digits = 2) {
  if (val === null || val === undefined || val === '-') return '-';
  const num = Number(val);
  return isNaN(num) ? val : num.toFixed(digits);
}

// 基于单位/项目的统一格式化：
// - 单位为 mm → 保留三位小数
// - 速度/轧制力/电机功率 → 取整
// - 其他 → 保留两位小数
function formatByRule(itemLabel: string | undefined, unitLabel: string | undefined, value: any) {
  if (value === null || value === undefined || value === '-') return '-';
  const num = Number(value);
  if (isNaN(num)) return value;
  let digits = 2;
  if (unitLabel === 'mm') {
    digits = 3;
  }
  if (itemLabel === '速度' || itemLabel === '轧制力' || itemLabel === '电机功率') {
    digits = 0;
  }
  return num.toFixed(digits);
}

function stopPolling() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}

async function fetchTableData() {
  try {
    const res = await rollingSimulationApi.HMI({
      action: "get_tags",
      operator: "abc",
      terminal: "FM_01",
      body: [{ tagName: "TCM_CoilData", timestamp: 0 }]
    });
    const coilList = (res?.data?.results?.[0]?.value || []).slice(0, 2);
    tableData.value = coilList.map((item: any, idx: number) => ({
      ITEM: idx === 0 ? "当前卷" : "下一卷",
      COIL_ID: item.ENTID ?? '-',
      STEEL_GRADE: item.STEELGRADE ?? '-',
      EN_WIDTH: formatNumber(item.IN_MAT_WIDTH),
      EN_THICK: formatNumber(item.IN_MAT_THICK),
      EX_THICK: formatNumber(item.OUT_MAT_THICK),
      YP: formatNumber(item.YS, 0),
      YPINDEX: formatNumber(item.YP_CLASS, 0),
      WIDINDEX: formatNumber(item.EXWIDTH_CLASS, 0),
      THKINDEX: formatNumber(item.EXTHK_CLASS, 0),
    }));
  } catch (e) {
    tableData.value = [];
    stopPolling();
  }
}

// 记录上一次柱状图数据
let lastChartData = ref("");

// 添加防抖函数
function debounce(fn: Function, delay: number) {
  let timer: any = null;
  return function (this: any, ...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 使用防抖处理数据更新
const debouncedFetchMiddleTableData = debounce(async () => {
  try {
    const res = await rollingSimulationApi.rest({ name: "TCM2280_RealData" });
    const obj = JSON.parse(JSON.stringify(res.data)); // 深拷贝避免引用问题
    const data = [
      { ITEM: "出口厚度", UNIT: "mm" },
      { ITEM: "速度", UNIT: "m/min" },
      { ITEM: "张力", UNIT: "kN" },
      { ITEM: "轧制力", UNIT: "kN" },
      { ITEM: "辊缝", UNIT: "mm" },
      { ITEM: "前滑", UNIT: "Per Uint" },
      { ITEM: "下一卷轧制力", UNIT: "kN" },
      { ITEM: "转矩", UNIT: "kN·m" },
      { ITEM: "电机功率", UNIT: "kW" },
      { ITEM: "工作辊弯辊力", UNIT: "kN" },
      { ITEM: "中间辊弯辊力", UNIT: "kN" },
      { ITEM: "辊径", UNIT: "mm" },
      { ITEM: "工作辊辊径", UNIT: "mm" },
      { ITEM: "窜辊量", UNIT: "mm" },
    ];
    // 清空并重新初始化 middleTableData
    middleTableData.value = [];
    data.forEach(item => {
      middleTableData.value.push({ ...item });
    });
    

    // 按照arr映射赋值
    for (let i = 0; i < middleTableData.value.length; i++) {
      // 电机功率行使用 arr[6] 的映射，其他行使用对应的 arr[i]
      const mappingIndex = middleTableData.value[i].ITEM === '电机功率' ? 6 : i;

      const itemLabel = middleTableData.value[i].ITEM;
      const unitLabel = middleTableData.value[i].UNIT;

      middleTableData.value[i].STD5A = arr[mappingIndex][0] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][0]]) : "-";
      middleTableData.value[i].STD4A = arr[mappingIndex][1] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][1]]) : "-";
      middleTableData.value[i].STD3A = arr[mappingIndex][2] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][2]]) : "-";
      middleTableData.value[i].STD2A = arr[mappingIndex][3] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][3]]) : "-";
      middleTableData.value[i].STD1A = arr[mappingIndex][4] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][4]]) : "-";
      middleTableData.value[i].BEFORE = arr[mappingIndex][5] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][5]]) : "-";
      middleTableData.value[i].STD5 = arr[mappingIndex][6] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][6]]) : "-";
      middleTableData.value[i].STD4 = arr[mappingIndex][7] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][7]]) : "-";
      middleTableData.value[i].STD3 = arr[mappingIndex][8] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][8]]) : "-";
      middleTableData.value[i].STD2 = arr[mappingIndex][9] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][9]]) : "-";
      middleTableData.value[i].STD1 = arr[mappingIndex][10] ? formatByRule(itemLabel, unitLabel, obj[arr[mappingIndex][10]]) : "-";
    }


    // 电机功率实际值特殊处理
    const powerRow = middleTableData.value.find(row => row.ITEM === '电机功率');
    if (powerRow) {
      ['STD5A', 'STD4A', 'STD3A', 'STD2A', 'STD1A'].forEach((key, idx) => {
        const raw = Number(powerRow[key]);
        if (!isNaN(raw)) {
          const percent = Math.round(raw);
          let base = raw / 100;
          if (idx === 4) {
            base = base * 5470;
          } else {
            base = base * 7800;
          }
          const result = Math.round(base);
          powerRow[key] = `${result}(${percent}%)`;
        }
      });
    }

    // 获取计算值
    const currentCoilId = tableData.value?.[0]?.COIL_ID;
    if (currentCoilId) {
      const calcRes = await rollingSimulationApi.getAcidPlanData({
        volumeNum: currentCoilId,
        pageIndex: "1",
        pageSize: "30"
      });
      
      if (calcRes?.data?.data?.length > 0) {
        const calcData = calcRes.data.data[0];
        middleTableData.value.forEach(row => {
          switch (row.ITEM) {
            case '出口厚度':
              row.STD5B = formatByRule('出口厚度', 'mm', calcData.exiTthk5);
              row.STD4B = formatByRule('出口厚度', 'mm', calcData.exiTthk4);
              row.STD3B = formatByRule('出口厚度', 'mm', calcData.exiTthk3);
              row.STD2B = formatByRule('出口厚度', 'mm', calcData.exiTthk2);
              row.STD1B = formatByRule('出口厚度', 'mm', calcData.exiTthk1);
              break;
            case '速度':
              row.STD5B = formatByRule('速度', undefined, calcData.speed5);
              row.STD4B = formatByRule('速度', undefined, calcData.speed4);
              row.STD3B = formatByRule('速度', undefined, calcData.speed3);
              row.STD2B = formatByRule('速度', undefined, calcData.speed2);
              row.STD1B = formatByRule('速度', undefined, calcData.speed1);
              break;
            case '前滑':
              row.STD5B = formatByRule('前滑', undefined, calcData.forSlip5);
              row.STD4B = formatByRule('前滑', undefined, calcData.forSlip4);
              row.STD3B = formatByRule('前滑', undefined, calcData.forSlip3);
              row.STD2B = formatByRule('前滑', undefined, calcData.forSlip2);
              row.STD1B = formatByRule('前滑', undefined, calcData.forSlip1);
              break;
            case '轧制力':
              row.STD5B = formatByRule('轧制力', undefined, calcData.rollingForceSet5 * 10);
              row.STD4B = formatByRule('轧制力', undefined, calcData.rollingForceSet4 * 10);
              row.STD3B = formatByRule('轧制力', undefined, calcData.rollingForceSet3 * 10);
              row.STD2B = formatByRule('轧制力', undefined, calcData.rollingForceSet2 * 10);
              row.STD1B = formatByRule('轧制力', undefined, calcData.rollingForceSet1 * 10);
              break;
            case '张力':
              row.STD5B = formatByRule('张力', undefined, calcData.tenSion5);
              row.STD4B = formatByRule('张力', undefined, calcData.tenSion4);
              row.STD3B = formatByRule('张力', undefined, calcData.tenSion3);
              row.STD2B = formatByRule('张力', undefined, calcData.tenSion2);
              row.STD1B = formatByRule('张力', undefined, calcData.tenSion1);
              break;
            case '工作辊弯辊力':
              row.STD5B = formatByRule('工作辊弯辊力', undefined, calcData.wbEnd5);
              row.STD4B = formatByRule('工作辊弯辊力', undefined, calcData.wbEnd4);
              row.STD3B = formatByRule('工作辊弯辊力', undefined, calcData.wbEnd3);
              row.STD2B = formatByRule('工作辊弯辊力', undefined, calcData.wbEnd2);
              row.STD1B = formatByRule('工作辊弯辊力', undefined, calcData.wbEnd1);
              break;
            case '电机功率':
              // 只设置计算值，不影响实际值
              row.STD5B = formatByRule('电机功率', undefined, calcData.motorPower5);
              row.STD4B = formatByRule('电机功率', undefined, calcData.motorPower4);
              row.STD3B = formatByRule('电机功率', undefined, calcData.motorPower3);
              row.STD2B = formatByRule('电机功率', undefined, calcData.motorPower2);
              row.STD1B = formatByRule('电机功率', undefined, calcData.motorPower1);
              break;
            case '辊缝':
              row.STD5B = formatByRule('辊缝', 'mm', calcData.gap5);
              row.STD4B = formatByRule('辊缝', 'mm', calcData.gap4);
              row.STD3B = formatByRule('辊缝', 'mm', calcData.gap3);
              row.STD2B = formatByRule('辊缝', 'mm', calcData.gap2);
              row.STD1B = formatByRule('辊缝', 'mm', calcData.gap1);
              break;
            case '压下率':
              row.STD5B = formatByRule('压下率', undefined, calcData.redsFinal5);
              row.STD4B = formatByRule('压下率', undefined, calcData.redsFinal4);
              row.STD3B = formatByRule('压下率', undefined, calcData.redsFinal3);
              row.STD2B = formatByRule('压下率', undefined, calcData.redsFinal2);
              row.STD1B = formatByRule('压下率', undefined, calcData.redsFinal1);
              break;
            default:
              break;
          }
        });
      }
    }
    middleTableDataall.value = middleTableData.value;
  } catch (e) {
    middleTableData.value = [];
    stopPolling();
  }
}, 500);

function getBarGroupData(row: Record<string, any>, itemTitle?: string): { stdB: number[]; std: number[]; stdA: (number | string)[] } {
  let stdB = ['STD5B', 'STD4B', 'STD3B', 'STD2B', 'STD1B'].map(k => Number(row?.[k]) || 0);
  let std = ['STD5', 'STD4', 'STD3', 'STD2', 'STD1'].map(k => Number(row?.[k]) || 0);
  let stdA: (number | string)[] = ['STD5A', 'STD4A', 'STD3A', 'STD2A', 'STD1A'].map(k => Number(row?.[k]) || 0);

  // 功率特殊处理
  if (itemTitle === '电机功率') {
    stdA = stdA.map((val, idx) => {
      const percent = Math.round(Number(val));
      let base = Number(val) / 100;
      // S1（最后一个）
      if (idx === 4) {
        base = base * 5470;
      } else {
        base = base * 7800;
      }
      const result = Math.round(base);
      return `${result}(${percent}%)`;
    });
  }

  // y 轴柱状图需为数字；若是字符串（如 功率 实际值“数值(%)”），保持字符串用于 tooltip 展示
  return { stdB, std, stdA };
}

function fetchChartData() {
  // 取中间表格的相关行
  const rollForceRow = middleTableDataall.value.find((row) => row.ITEM === '轧制力') || {};
  const tensionRow = middleTableDataall.value.find((row) => row.ITEM === '张力') || {};
  // 弯辊力用工作辊弯辊力（第11行，下标10）
  const bendForceRow = middleTableDataall.value[8] || {}; // 工作辊弯辊力
  const speedRow = middleTableDataall.value.find((row) => row.ITEM === '速度') || {};
  const powerRow = middleTableDataall.value.find((row) => row.ITEM === '电机功率') || {};

  chartList.value = [
    { title: '轧制力', ...getBarGroupData(rollForceRow, '轧制力') },
    { title: '张力', ...getBarGroupData(tensionRow, '张力') },
    { title: '弯辊力', ...getBarGroupData(bendForceRow, '弯辊力') },
    { title: '速度', ...getBarGroupData(speedRow, '速度') },
    { title: '电机功率', ...getBarGroupData(powerRow, '电机功率') },
  ];
}

function renderCharts() {
  chartList.value.forEach((item, idx) => {
    if (chartRefs[idx]) {
      if (!chartInstances[idx]) {
        chartInstances[idx] = echarts.init(chartRefs[idx]);
      }
      // 计算所有series的最小值
      const allVals = [...item.stdB, ...item.std, ...item.stdA];
      let minY = Math.min(...allVals);
      if (isNaN(minY) || minY > 0) minY = 0;
      chartInstances[idx].setOption({
        backgroundColor: '#183272',
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicInOut',
        animationThreshold: 2000,
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function (params: any[]) {
            let tooltipText = `${params[0].name}<br/>`;
            params.forEach(param => {
              tooltipText += `${param.marker}${param.seriesName}: ${param.value}<br/>`;
            });
            return tooltipText;
          }
        },
        legend: {
          data: ['计算值', '设定值', '实际值'],
          top: '5%',
          textStyle: { color: '#b8e8ff', fontSize: 12 }
        },
        grid: { left: '8%', right: '8%', bottom: '10%', top: '18%', containLabel: true },
        xAxis: [{
          type: 'category',
          data: ['S5', 'S4', 'S3', 'S2', 'S1'],
          axisTick: { alignWithLabel: true },
          axisLabel: { color: '#b8e8ff', fontSize: 11 },
          axisLine: { lineStyle: { color: '#3a5a8a' } }
        }],
        yAxis: [{
          type: 'value',
          axisLabel: { color: '#b8e8ff', fontSize: 11 },
          splitLine: { lineStyle: { color: '#3a5a8a', opacity: 0.3 } },
          axisLine: { lineStyle: { color: '#3a5a8a' }},
          min: minY
        }],
        series: [
          {
            name: '计算值',
            type: 'bar',
            barWidth: '28%',
            data: item.stdB,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ffd700' },
                { offset: 1, color: 'rgba(255,215,0,0.2)' }
              ]),
              borderRadius: [6, 6, 0, 0],
              shadowColor: 'rgba(255,215,0,0.3)',
              shadowBlur: 8
            }
          },
          {
            name: '设定值',
            type: 'bar',
            barWidth: '28%',
            data: item.std,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#42b4ff' },
                { offset: 1, color: 'rgba(11, 41, 96, 0.8)' }
              ]),
              borderRadius: [6, 6, 0, 0],
              shadowColor: 'rgba(66, 180, 255, 0.5)',
              shadowBlur: 10
            }
          },
          {
            name: '实际值',
            type: 'bar',
            barWidth: '28%',
            data: item.stdA.map((v: string | number) => typeof v === 'string' ? v : Math.round(v)),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#00ff9d' },
                { offset: 1, color: 'rgba(11, 41, 96, 0.8)' }
              ]),
              borderRadius: [6, 6, 0, 0],
              shadowColor: 'rgba(0,255,157,0.3)',
              shadowBlur: 8
            }
          }
        ]
      }, false);
    }
  });
}

// 监听middleTableData变化，只有有变化时才刷新柱状图
watch(middleTableData, () => {
  fetchChartData();
  const chartDataStr = JSON.stringify(chartList.value);
  if (chartDataStr !== lastChartData.value) {
    nextTick(renderCharts);
    lastChartData.value = chartDataStr;
  }
}, { deep: true });

// 在 script setup 部分添加计算属性
const thicknessValues = computed(() => {
  const row = middleTableData.value.find((r: any) => r.ITEM === '出口厚度') || {};
  return {
    BEFORE: tableData.value?.[0]?.EN_THICK ?? '-',  // 取当前卷的入口厚度
    STD1A: row.STD1A ?? '-',
    STD4A: row.STD4A ?? '-',
    STD5A: row.STD5A ?? '-',
  };
});

onBeforeMount(() => {
  useUserStore().setTagNav(data.value);
  fetchTableData();
}),

onMounted(() => {
  fetchTableData();
  debouncedFetchMiddleTableData();
  timer = setInterval(() => {
    fetchTableData();
    debouncedFetchMiddleTableData();
  }, 2000);
  window.addEventListener('resize', renderCharts);
});

onUnmounted(() => {
  stopPolling();
  chartInstances.forEach(c => c && c.dispose());
  window.removeEventListener('resize', renderCharts);
});
</script>

<style scoped>
/* --- Base & Layout --- */
.arpe-container {
  position: relative;
  background: url('../../assets/images/body-bg.jpg') no-repeat center center;
  background-size: cover;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  color: #fff;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  display: flex;
  flex-direction: column;
}

.arpe-header {
  flex: 0 0 6vh;
  background-image: url('../../assets/images/head-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 0.5vh;
  z-index: 10;
}

.arpe-title {
  font-size: 1.3vw;
  color: #ffffff;
  text-align: center;
  letter-spacing: 0.2vw;
  text-shadow: 0 0 10px #42b4ff, 0 0 20px #0a2466;
}

.arpe-content-layout {
  height: 94vh;
  /* header 6vh + 94vh = 100vh */
  min-height: 0;
  display: flex;
  flex-direction: column;
  width: 100%;
  margin-top: -45px;
  padding: 0 1vw;
  box-sizing: border-box;
}

.arpe-section {
  min-height: 0;
  max-height: 100%;
  overflow: hidden;
}

.top-section {
  height: 25%;
  min-height: 0;
  max-height: 25%;
}

.top-flex {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
}

.thickness-card {
  position: absolute;
  min-width: 50px;
  z-index: 20;
  background: linear-gradient(135deg, rgba(24, 50, 114, 0.8) 0%, rgba(14, 30, 82, 0.9) 100%);
  border: 1px solid rgba(66, 180, 255, 0.3);
  border-radius: 4px;
  padding: 4px 8px;
  box-shadow: 0 0 10px rgba(66, 180, 255, 0.2);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  animation: glow 2s infinite alternate;
}

.thickness-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 0 15px rgba(66, 180, 255, 0.4);
  border-color: rgba(66, 180, 255, 0.6);
}

.thickness-card p {
  margin: 0;
  font-size: 11px;
  color: #c0d8ff;
  text-shadow: 0 0 5px rgba(66, 180, 255, 0.3);
  letter-spacing: 0.5px;
  line-height: 1.2;
}

.thickness-card p:first-child {
  color: #42b4ff;
  font-weight: bold;
  margin-bottom: 2px;
  font-size: 11px;
}

.thickness-card p:last-child {
  font-size: 12px;
  font-weight: 500;
}

.thickness-card::before {
  content: '';
  position: absolute;
  top: -1px;
  left: -1px;
  right: -1px;
  bottom: -1px;
  background: linear-gradient(45deg, transparent, rgba(66, 180, 255, 0.3), transparent);
  border-radius: 4px;
  z-index: -1;
  animation: borderGlow 2s linear infinite;
}

@keyframes glow {
  from {
    box-shadow: 0 0 8px rgba(66, 180, 255, 0.2);
  }
  to {
    box-shadow: 0 0 15px rgba(66, 180, 255, 0.4);
  }
}

@keyframes borderGlow {
  0% {
    opacity: 0.3;
  }
  50% {
    opacity: 0.8;
  }
  100% {
    opacity: 0.3;
  }
}

.thickness-card-before {
  left: 40%;
  top: 6%;
}

.thickness-card-s1 {
  left: 33%;
  top: 6%;
}

.thickness-card-s4 {
  left: 16%;
  top: 6%;
}

.thickness-card-s5 {
  left: 7%;
  top: 6%;
}

.top-svg {
  flex: 1 1 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  max-width: 50%;
}

.top-svg img {
  max-width: 80%;
  max-height: 80%;
  object-fit: contain;
  background: transparent;
  filter: drop-shadow(0 0 18px #42b4ff) drop-shadow(0 0 8px #0a2466);
  border-radius: 16px;
}

.top-table {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  max-width: 50%;
}

.table-title {
  font-size: 1vw;
  font-weight: bold;
  margin-bottom: 0.5vh;
  color: #fff;
}

:deep(.el-table__border-left-patch),
:deep(.el-table__border-right-patch),
:deep(.el-table__border-top-patch),
:deep(.el-table__border-bottom-patch) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  width: 0 !important;
  height: 0 !important;
  display: none !important;
}

:deep(.el-table::before),
:deep(.el-table::after),
:deep(.el-table__inner-wrapper::before),
:deep(.el-table__inner-wrapper::after) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  display: none !important;
  content: none !important;
}

:deep(.el-table) {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  width: 100% !important;
  max-width: 100% !important;
  table-layout: fixed !important;
}

:deep(.el-table__inner-wrapper) {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}

:deep(.el-table tr:nth-child(odd)) {
  background-color: #0f2142 !important;
}

:deep(.el-table tr:nth-child(even)) {
  background-color: #142a52 !important;
}

:deep(.el-table th.el-table__cell),
:deep(.el-table td.el-table__cell) {
  font-size: 10px !important;
}

:deep(.el-table th.el-table__cell) {
  color: #42b4ff !important;
  background-color: rgba(24, 50, 114, 0.9) !important;
  border-bottom: 1px solid rgba(66, 180, 255, 0.2) !important;
  font-size: 13px;
  font-weight: bold;
  text-align: center;
  padding: 8px 0;
}

:deep(.el-table td.el-table__cell) {
  color: #fff !important;
  background-color: transparent !important;
  border-bottom: 1px solid rgba(66, 180, 255, 0.1) !important;
  border-right: 1px solid rgba(66, 180, 255, 0.1) !important;
  font-size: 13px;
  text-align: center;
  padding: 6px 0;
  transition: all 0.3s ease;
}

/* 添加计算值的过渡效果 */
:deep(.el-table td.el-table__cell[class*="STD"][class*="B"]) {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: rgba(66, 180, 255, 0.15) !important;
  color: #fff !important;
  transform: scale(1.01);
  box-shadow: 0 0 10px rgba(66, 180, 255, 0.2);
}

:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  scrollbar-color: rgba(66, 180, 255, 0.5) rgba(20, 42, 82, 0.5);
  width: 100% !important;
  max-width: 100% !important;
  overflow-x: hidden !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: rgba(20, 42, 82, 0.5);
  border-radius: 3px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: rgba(66, 180, 255, 0.5);
  border-radius: 3px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background-color: rgba(66, 180, 255, 0.8);
}

:deep(.el-table .el-table__cell) {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  font-size: clamp(10px, 0.8vw, 14px) !important;
  padding: 0.3vw 0.1vw !important;
  min-width: 0 !important;
  max-width: 100vw !important;
}

:deep(.el-table .cell) {
  display: block;
  width: 100%;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

.middle-section {
  height: 50%;
  min-height: 0;
  max-height: 50%;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.bottom-section {
  height: 25%;
  min-height: 0;
  max-height: 25%;
  margin-top: 45px;
}

.bottom-charts {
  display: flex;
  height: 100%;
  gap: 24px;
  justify-content: space-between;
  align-items: stretch;
}

.chart-card {
  flex: 1 1 0;
  background: rgba(24, 50, 114, 0.85);
  border-radius: 12px;
  box-shadow: 0 0 18px 2px #42b4ff33;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px 8px 8px;
  min-width: 0;
}

.chart-title {
  color: #42b4ff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  text-shadow: 0 0 8px #42b4ff;
}

.echart-box {
  width: 100%;
  height: 100%;
  min-width: 0;
}
</style>
